package ui.util
{
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.geom.Rectangle;
	import flash.net.URLLoader;
	import flash.net.URLRequest;

	public class JSONTextureManager extends EventDispatcher
	{
		public static const COMPLETE:String = "Complete";
		
		private var root:String;
		private var urlLoader:URLLoader;
		private var map:Object;

		public function JSONTextureManager() {
			urlLoader = new URLLoader();
		}
		
		public function loadJSON(fileName:String, root:String = null):void {
			urlLoader.addEventListener(Event.COMPLETE, onLoaded);
			urlLoader.load((new URLRequest(fileName)));
			this.root = root;
		}
		
		public function getObject(name:String):Object {
			if (map != null) {
				return returnRoot(name);
			} else {
				return null;
			}
		}
		
		public function getRectangle(name:String):Rectangle {
			if (map != null) {
				var obj:Object = returnRoot(name);
				return new Rectangle(obj.frame.x, obj.frame.y, obj.frame.w, obj.frame.h);
			} else {
				return null;
			}
		}
		
		private function onLoaded(event:Event):void {
			urlLoader.removeEventListener(Event.COMPLETE, onLoaded);
			map = JSON.parse(urlLoader.data);
			dispatchEvent(new Event(COMPLETE));
		}
		
		private function returnRoot(name:String):Object {
			if (root != null) {
				return map[root][name];
			} else {
				return map[name];
			}
		}
	}
}